<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleForm({qsType:'2'})" v-auth="'btn:add:qiashang'">
          <Icon icon="fluent:add-12-filled" /> {{ t('发起申请') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ id: record.id })">
          {{ record.projectname }}
        </a>
      </template>
      <template #projectno="{ record }">
        <!-- <a @click="handleDetailsForm(record)">
          <span style="text-decoration: underline; margin-right: 5px">查看</span>
        </a>
        {{ record.projectno }} -->
        <a @click="handleDetailsForm(record)">
          {{ record.projectno }}
        </a>
        
      </template>
      <template #switch="{ record }">
        <a-switch disabled v-model:checked="record.isInvolvewatermeter" />
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <BpmRuntimeTrace @register="registerTraceModal" />

    <component
      :is="inputFormComponent"
      v-model:visible="inputFormVisible"
      @register="registerDrawerBpmMyTask"
      @success="handleSuccess"
    />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsDesignQzNegotiList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent,ref,ComponentOptions,shallowRef, onMounted} from 'vue';
  import { bpmTaskDefForm } from '/@/api/bpm/myTask';
  import { dynamicImport } from '/@/router/helper/routeHelper';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import qs from 'qs';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { pmNegotiationDelete, pmNegotiationListData } from '/@/api/design/negoti/pmNegotiation';
  import { getDesignVisaKey } from '/@/api/zfgsCommon/zfgsCommon';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { BpmRuntimeTrace } from '/@/components/Bpm';
  import { FormProps } from '/@/components/Form';
  import { customListData, listSet } from '/@/api/test/testData';
  import { schemasData, tabConfigData } from '/@/utils/custom';

  import InputForm from './form.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useGlobSetting } from '/@/hooks/setting';
  const userStore = useUserStore();

  const { t } = useI18n('design.negoti.pmNegotiation');
  const { showMessage } = useMessage();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('洽商单管理'),
  };

  let tableColumns = ref<any>([]);
  let designchangereasonid = ref<any>('');

  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});

  const searchForm = ref<FormProps>({
    baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    schemas: [],
  });

  // const searchForm: FormProps = {
  //   baseColProps: { lg: 6, md: 8 },
  //   labelWidth: 90,
  //   schemas: [
  //     {
  //       label: t('工程编号'),
  //       field: 'projectno',
  //       component: 'Input',
  //     },
  //     {
  //       label: t('工程名称'),
  //       field: 'projectname',
  //       component: 'Input',
  //     },
  //     {
  //       label: t('变更类型'),
  //       field: 'designchangereasonid',
  //       component: 'Select',
  //       componentProps: {
  //         dictType: 'zf_designChg_reson_type',
  //         allowClear: true,
  //       },
  //     },
  //     {
  //       label: t('变更原因'),
  //       field: 'remarks',
  //       component: 'Input',
  //     },
  //     {
  //       label: t('执行状态'),
  //       field: 'isReject',
  //       component: 'Select',
  //       componentProps: {
  //         dictType: 'zf_Negotiation_Reject_status',
  //         allowClear: true,
  //       },
  //     },
  //   ],
  // };

  // const tableColumns: BasicColumn[] = [
  //   {
  //     title: t('审批状态'),
  //     dataIndex: 'status',
  //     key: 'a.status',
  //     sorter: true,
  //     width: 100,
  //     align: 'left',
  //     // dictType: 'sys_search_status',
  //     dictType: 'bpm_biz_status',
  //     fixed:'left'
  //   },
  //   {
  //     title: t('洽商单编号'),
  //     dataIndex: 'djno',
  //     key: 'a.negotiationcode',
  //     sorter: true,
  //     width: 120,
  //     align: 'left',
  //     fixed:'left'
  //   },
  //   {
  //     title: t('工程编号'),
  //     dataIndex: 'projectno',
  //     key: 'a.projectcode',
  //     sorter: true,
  //     width: 130,
  //     align: 'left',
  //     slot: 'firstColumn',

  //   },
  //   {
  //     title: t('工程名称'),
  //     dataIndex: 'projectname',
  //     key: 'a.name',
  //     sorter: true,
  //     width: 200,
  //     align: 'left',
  //   },
  //   {
  //     title: t('变更类型'),
  //     dataIndex: 'designchangereasonid',
  //     key: 'a.designchangereasonid',
  //     sorter: true,
  //     width: 100,
  //     align: 'center',
  //     dictType: 'zf_designChg_reson_type',
  //   },
  //   {
  //     title: t('变更原因'),
  //     dataIndex: 'remarks',
  //     key: 'a.negotiationdetail',
  //     sorter: true,
  //     width: 160,
  //     align: 'left',
  //   },
  //   {
  //     title: t('创建时间'),
  //     dataIndex: 'createDate',
  //     key: 'a.createtime',
  //     sorter: true,
  //     width: 100,
  //     align: 'center',
  //   },
  //   {
  //     title: t('涉及水表'),
  //     dataIndex: 'isInvolvewatermeter',
  //     key: 'a.isinvolvewatermeter',
  //     sorter: true,
  //     width: 100,
  //     align: 'center',
  //     slot: 'switch',
  //   },
  //   {
  //     title: t('驳回原因'),
  //     dataIndex: 'backResult',
  //     key: 'a.backresult',
  //     sorter: true,
  //     width: 160,
  //     align: 'left',
  //   },
  //   {
  //     title: t('驳回时间'),
  //     dataIndex: 'backResultDate',
  //     key: 'a.backresultdate',
  //     sorter: true,
  //     width: 100,
  //     align: 'center',
  //   },
  //   {
  //     title: t('驳回人'),
  //     dataIndex: 'backResultPerson',
  //     key: 'a.backresultperson',
  //     sorter: true,
  //     width: 100,
  //     align: 'left',
  //   },
  //   {
  //     title: t('审核结果'),
  //     dataIndex: 'checkResult',
  //     key: 'a.checkresult',
  //     sorter: true,
  //     width: 100,
  //     align: 'center',
  //     fixed:'right'
  //   },
  //   {
  //     title: t('接口错误返回信息'),
  //     dataIndex: 'errorContent',
  //     key: 'a.errorcontent',
  //     sorter: true,
  //     width: 160,
  //     align: 'left',
  //   },
  //   {
  //     title: t('执行状态'),
  //     dataIndex: 'isReject',
  //     key: 'a.isreject',
  //     sorter: true,
  //     width: 100,
  //     align: 'center',
  //     dictType: 'zf_Negotiation_Reject_status',
  //     fixed:'right'
  //   },
  // ];

  const actionColumn: BasicColumn = {
    width: 160,
    align: 'left',
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑洽商单'),
        onClick: handleForm.bind(this, { id: record.id }),
        auth: 'btn:edit:qiashang',
        ifShow: () => record.status == '9',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除洽商单'),
        popConfirm: {
          title: t('是否确认删除洽商单'),
          confirm: handleDelete.bind(this, { id: record.id }),
        },
        auth: 'btn:delete:qiaoshang',
        ifShow: () => record.status == '9',
      },
      {
        icon: 'fluent:flowchart-20-regular',
        title: t('流程追踪'),
        onClick: handleTrace.bind(this, record),
        ifShow: () => record.status != '9',
      },
      {
        icon: 'ant-design:download-outlined',
        title: t('下载洽商单'),
        auth: 'btn:down:qiashang',
        onClick: handleDownload.bind(this, record.id),
      },
      {
        icon: 'mdi:checkbox-marked-outline',
        title: t('任务办理'),
        onClick: handleBpmMyTask.bind(this, { id: record.id }),
        ifShow: () => record.status == '4' || record.status == '5' || record.status == '6',
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, getForm, setProps }] = useTable({
    // api: pmNegotiationListData,
    // beforeFetch: (params) => {
    //   return params;
    // },
    afterFetch: (list) => {
      list = list.map((item) => {
        item.isInvolvewatermeter = item.isInvolvewatermeter == 'true' ? true : false;
        return item;
      });
      return list;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    immediate: false,
  });

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleDelete(record: Recordable) {
    const res = await pmNegotiationDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  function handleSuccess() {
    reload();
  }

  const [registerDrawerBpmMyTask, { setDrawerData }] = useDrawer();
  const inputFormComponent = shallowRef<Nullable<any>>(null);
  const inputFormVisible = ref<Boolean>(false);

  async function handleBpmMyTask(record: Recordable) {
    const data = await bpmTaskDefForm({ formKey: 'Flow_PmNegotiation', bizKey: record.id });
    if (data.result == 'true') {
      const url = data.pcUrl;
      const idx = url.indexOf('?');
      // component
      let component: ReturnType<typeof defineComponent>;
      const compStr = idx == -1 ? url : url.substring(0, idx);
      if (compStr && compStr != '') {
        const imp = dynamicImport(compStr);
        if (imp) component = createAsyncComponent(imp);
      }
      // params
      let params = {};
      const paramStr = idx == -1 ? '' : url.substring(idx + 1);
      if (paramStr && paramStr != '') {
        params = qs.parse(paramStr);
      }
      // open
      if (component) {
        inputFormComponent.value = component;
        inputFormVisible.value = true;
        setDrawerData(params);
      }
    } else {
      showMessage(data.message);
    }
  }

  const [registerTraceModal, { openModal: traceModel }] = useModal();

  function handleTrace(record: Recordable) {
    traceModel(true, { formKey: 'Flow_PmNegotiation', bizKey: record.id });
  }

  onMounted(async () => {
    designchangereasonid.value = await getDesignVisaKey();
    
    const res = await listSet({ viewCode: 'zfgs_design_negoti_list001' });
    // title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;
    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery?.queryCols);
    searchForm.value.schemas.forEach((item) => {
      if (item.field == 'designchangereasonid') {
        item.show = false;
      }
    });
    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头
    // butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    // actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮
    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    await setProps({
      api: customListData,
      beforeFetch: (params) => {
        params.url = listTabConfig.value.api;
        // params.designchangereasonid = designchangereasonid.value;
        params.qsType = '2'
        return params;
      },
      autoCreateKey: listTabConfig.value.autoCreateKey,
      bordered: listTabConfig.value.bordered,
      canResize: listTabConfig.value.canResize,
      clearSelectOnPageChange: listTabConfig.value.clearSelectOnPageChange,
      clickToRowSelect: listTabConfig.value.clickToRowSelect,
      ellipsis: listTabConfig.value.ellipsis,
      emptyDataIsShowTable: listTabConfig.value.emptyDataIsShowTable,
      inset: listTabConfig.value.inset,
      isTreeTable: listTabConfig.value.isTreeTable,
      pagination: listTabConfig.value.pagination,
      showIndexColumn: listTabConfig.value.showIndexColumn,
      showSummary: listTabConfig.value.showSummary,
      showTableSetting: listTabConfig.value.showTableSetting,
      striped: listTabConfig.value.striped,
      useSearchForm: listTabConfig.value.useSearchForm,
      tableSetting: listTabConfig.value.tableSetting,
      titleHelpMessage: listTabConfig.value.titleHelpMessage,
      maxHeight: listTabConfig.value.maxHeight,
      resizeHeightOffset: listTabConfig.value.resizeHeightOffset,
    });
    // if (!listTabConfig.value.immediate) {
    //   reload();
    // }
    handleProjecte();
  });
  function handleDetailsForm(record: Recordable) {
    router.push({
      path: '/proj/info/pmProjectinformation/detailsForm',
      query: {
        id: record.projInfo.id,
        code: record.projectno,
        tabTitle: `项目详情(${record.projectno})`,
      },
    });
  }
  async function handleProjecte() {
    await getForm().setFieldsValue({
      projectno: userStore.getProjecte.code,
    });
    reload();
    await getForm().setFieldsValue({
      projectno: userStore.getProjecte.code,
    });
  }

  async function handleDownload(id: string) {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + `/design/negoti/pmNegotiation/download?id=${id}`,
      target: '_self',
    });
  }
</script>
